package com.onepiece.shipelves.common.myutils.search;

public class BSearch {

    public static void main(String[] args) {
        int[] nums = {1,2,2,3,4,5,6,7,8,11,15};
        int i = bSearch(nums, 2);
        System.out.println(i);

    }

    //查找第一个值等于给定值的元素,循环条件用low和high比较比较好
    //因为要查找第一个值，所以在相等的时候判断是不是第一个，如果不是就往前继续查找
    private static int bSearch(int[] nums, int i) {
        int low = 0, high = nums.length - 1;
        while (low <= high){//使用=是刚好就是二分最后变一个元素的那个位置是
            int mid = low +((high - low) >> 1);
            if(nums[mid] > i){
                high = mid - 1;
            }else if(nums[mid] < i){
                low = mid + 1;

            }else {
                if(mid == 0 || nums[mid - 1] != i) return mid;
                high = mid - 1;
            }
        }
        return -1;
    }
}
